<template>
    <div ref="Chart" :style></div>
</template>
<script lang='ts' setup>
import { useDebounceFn } from '@vueuse/core';
import { inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
const Echarts = inject('echarts') as typeof import('echarts')

const Chart = ref()

const { option, width, height } = defineProps<{
    option: ECOption,
    width?: number,
    height?: number
}>()
let chart: echarts.ECharts;

const style = {
    Position: 'relative',
    width: width ? `${width}px` : '100%',
    height: height ? `${height}px` : '100%'
}


watch(() => option, (newValue, oldValue) => {
    chart.setOption(newValue, { notMerge: true });
}, { deep: true })

onMounted(() => {
    init()
    window.addEventListener('resize', useDebounceFn(resize, 200))
})

onBeforeUnmount(() => {
    if (chart) chart.dispose()
})


function resize() {
    chart.resize()
}

function init() {
    chart = Echarts.init(Chart.value)
    chart.setOption(option)
}

function getImg({
    type = 'png',
    pixelRatio = window.devicePixelRatio || 2
}: {
    type?: 'png' | 'jpeg';
    pixelRatio?: number
} = {}) {
    return chart.getDataURL({ type, pixelRatio })
}

defineExpose({
    getImg
})

</script>
<style lang='scss' scoped></style>